package xyz.zhouxf.rpc.transport.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxf.rpc.codec.CommonDecoder;
import xyz.zhouxf.rpc.codec.CommonEncoder;
import xyz.zhouxf.rpc.provider.ServiceProvider;
import xyz.zhouxf.rpc.provider.impl.DefaultServiceProvider;
import xyz.zhouxf.rpc.registry.ServiceDiscovery;
import xyz.zhouxf.rpc.registry.ServiceRegistry;
import xyz.zhouxf.rpc.registry.nacos.NacosServiceRegistry;
import xyz.zhouxf.rpc.serializer.RpcSerializer;
import xyz.zhouxf.rpc.serializer.impl.JsonSerializer;
import xyz.zhouxf.rpc.transport.AbstractRpcServer;
import xyz.zhouxf.rpc.transport.RpcServer;

/**
 * @author zhouxf
 * @date 2022/8/20
 */
@Slf4j
public class NettyServer extends AbstractRpcServer {

    public NettyServer(String host, int port) {
        this(host, port, RpcSerializer.getRpcSerializer(RpcSerializer.DEFAULT_SERIALIZER));
    }

    public NettyServer(String host, int port, RpcSerializer serializer) {
        serviceRegistry = new NacosServiceRegistry();
        serviceProvider = new DefaultServiceProvider();
        this.host = host;
        this.port = port;
        this.serializer = serializer;
        scanService();
    }


    @Override
    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                            ChannelPipeline pipeline = nioSocketChannel.pipeline();
                            pipeline.addLast(new CommonEncoder(serializer));
                            pipeline.addLast(new CommonDecoder());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            log.error("服务器启动错误：",e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
